#include "music_handler.h"

void handler::music_handler::handle_event(boost::shared_ptr<network::event> e)
{
	boost::shared_ptr<model::dom> node(e->node);
	if(node->name() != "client") {
		return;
	}
	cout << node->to_string() << endl;
	model::client clt(*node);
	clt.print();
	// optain lock
	boost::shared_ptr<boost::mutex> mon( 
		network::singletone<model::model_class>::get_monitor());
	boost::shared_ptr<model::model_class> model(
		network::singletone<model::model_class>::instance());
	boost::mutex::scoped_lock l(*mon);
	model->get_clients().push_back(clt);

	boost::shared_ptr<network::network_client> net_clt(
		network::singletone<network::network_client>::instance());
	(*net_clt)[_sock] = &model->get_clients().back();
}

void handler::music_handler::notify(const network::notifier *n)
{
	const network::receiver *r = dynamic_cast<const network::receiver *>(n);
	cout << "deleting a client..." << endl;
	if(!r) {
		return;
	}
	if(r->get_socket() != _sock) {
		return;
	}

	// optain data
	boost::shared_ptr<boost::mutex> _mon( 
		network::singletone<model::model_class>::get_monitor());
	boost::shared_ptr<network::network_client> clt(
		network::singletone<network::network_client>::instance());

	boost::shared_ptr<model::model_class> model(
		network::singletone<model::model_class>::instance());

	// locking the whole model-data
	boost::mutex::scoped_lock l(*_mon);
	// searching the client model data
	model::client *client = (*clt)[_sock];

	list<model::client> &list = model->get_clients();

	// removing the client model-data
	std::list<model::client>::iterator i = list.begin();
	std::list<model::client>::iterator next = i;
	while(i != list.end()) {
		++next;
		if(&(*i) == client) {
			list.erase(i);
		}
		i = next;
	}

	// containers, which are holding a reference to this object, should 
	// delete this reference...
	boost::shared_ptr<handler::music_handler> ptr(_this.lock());
	fire_listener();
	_this.reset();
}

